package cz.spock.core.service;

import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.googlecode.objectify.Key;

import cz.spock.core.dao.CoreDao;
import cz.spock.exception.DatabaseException;

/**
 * superclass for other service classes
 * 
 * service classes provides methods for controllers
 * 
 * provides toJson methods (expected to be used widely) using google's Gson
 * 
 * @author miso
 *
 */
@Component
public class BaseService {
    
    @Autowired
    protected CoreDao dao;

    //spring injection via setter
//    public void setDao(CoreDao dao) {
//        this.dao = dao;
//    }
    
    protected static final Logger log = Logger.getLogger(BaseService.class.getName());
    
    
    /**
     * generic method for saving data into datastore via objectify
     * CONTAINS DATA CHECK - should be used only for testing purposes or VERY CRITICAL writings...
     * 
     * @param <T>
     * @param object
     * @return persisted object with id
     */
    public <T> T save(T object) {
        Key<T> key = dao.ofy().put(object);
        object = null;
        object = dao.ofy().find(key);
        if(object == null) {
            log.fine("Fatal database error, BaseService, method save().");
            throw new DatabaseException("Database error, saving failed.");
        }
        return object;
    }
    
    
    /**
     * returns json representation of given object
     * 
     * @param <T>
     * @param object
     * @return
     */
    public <T> String toJson(T object) {
        Gson gson = new Gson();
        String result = gson.toJson(object);
        return result;
    }
    
    /**
     * returns json representation of object wrapped with given string
     * WRAP:OBJECTasJSON
     * "object1":{"field1":value1, ....}
     * 
     * @param <T>
     * @param object
     * @param wrap
     * @return
     */
    public <T> String toJson(T object, String wrap) {
        Gson gson = new Gson();
        String result = gson.toJson(object);
        return "\"" + wrap + "\"" + ":" + result;
    }
    
    /**
     * returns json error message
     * format
     * {"result":false, "data":{"message":"MESSAGE", "error":NUMBER}}
     * 
     * @param message
     * @param number
     * @return
     */
    public String errorToJson(String message, int number) {
        return "{\"result\":false, \"data\":{\"message\":\""+ message +"\", \"error\":" + number + "}}";
    }
    
    /**
     * returns json success message with given data string
     * format:
     * {"result":true, "data":{ DATA }}
     * 
     * for empty data use responseToJson(null)
     * 
     * @param data
     * @return
     */
    public String responseToJson(String data) {
        if(data == null) data = "";
        return "{\"result\":true, \"data\":{" + data + "}}";
    }

}
